package com.tsfyun.scm.gateway.util;


import cn.hutool.core.util.StrUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @CreateDate: Created in 2020/11/27 9:16
 */
public class IpUtils {

    public static String getIpAddress(ServerHttpRequest request) {
        String ip = request.getHeaders().getFirst("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("x-forwarded-for");
        }
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getHostName();
        }
        return ip;
    }

    /**
     * 是否移动端访问
     * @param request
     * @return
     */
    public static final List<String> MOBILE_AGENTS = new ArrayList<String>(){{
        add("Android");
        add("iPhone");
        add("Windows Phone");
        add("iPod");
        add("iPad");
        add("MQQBrowser");
        add("MicroMessenger");
    }};
    public static boolean isMobile(ServerHttpRequest request){
        String userAgent = StrUtil.nullToEmpty(request.getHeaders().getFirst("User-Agent")).toLowerCase();
        return MOBILE_AGENTS.stream().filter(r->userAgent.contains(r.toLowerCase())).count() > 0;
    }

}
